/*
 * Object pool code tutorial from
 * http://sourcemaking.com/design_patterns/object_pool
 *
 * Code used under non-commercial licence
 *
 *
 * DB.java makes use of the Object Pool OO design pattern.
 * This greatly speeds up the program and allows us to
 * reuse DB connections.
 */

/**
 *
 * @author steve
 */
import java.sql.*;
/**
 * 
 * @authors: Pat, Jamie, Kazu, Stephen, and Shaoyan
 */
public class DB extends DBConnectionPool<Connection> {

  private String dsn, usr, pwd;

  /**
   * 
   */
  public DB() {
    super();
    String driver = "com.mysql.jdbc.Driver";
    try {
      Class.forName(driver).newInstance();
    } catch (Exception e) {
      e.printStackTrace();
    }
    this.dsn = "jdbc:mysql://sql09.freemysql.net/seng330project";
    this.usr = "seng330";
    this.pwd = "fightingchickensco";
  }

  /**
   * 
   * @return
   */
  @Override
  protected Connection create() {
    try {
      return (DriverManager.getConnection(dsn, usr, pwd));
    } catch (SQLException e) {
      e.printStackTrace();
      return (null);
    }
  }

  /**
   * 
   * @param o
   */
  @Override
  public void expire(Connection o) {
    try {
      ((Connection) o).close();
    } catch (SQLException e) {
      e.printStackTrace();
    }
  }

  /**
   * 
   * @param o
   * @return
   */
  @Override
  public boolean validate(Connection o) {
    try {
      return (!((Connection) o).isClosed());
    } catch (SQLException e) {
      e.printStackTrace();
      return (false);
    }
  }

  /**
   * 
   * @param conn
   * @param query
   */
  public void putQuery(Connection conn, String query) {
        try {
            Statement s = conn.createStatement ();
            s.executeUpdate (query);
            s.close();
        }
        catch (Exception e) {
            //System.out.println( e.getMessage());
        }
    }

  /**
   * 
   * @param conn
   * @param query
   * @return
   */
  public ResultSet getQuery(Connection conn, String query) {
        ResultSet results = null;
        try {
            Statement s = conn.createStatement ();
            s.executeQuery (query);
            results = s.getResultSet ();
            //s.close();
        }
        catch (Exception e) {
            //System.out.println( e.getMessage());
        }
        return results;
    }
}